package com.leetcode.LeetCode精选TOP面试题;

/**
 * @author 覃国强
 * @date 2022-05-21 17:27
 */
public class 题库_0036_有效的数独 {

  static
  class Solution {
    public boolean isValidSudoku(char[][] board) {

      boolean[][] rows = new boolean[board.length][board.length];
      boolean[][] columns = new boolean[board.length][board.length];
      boolean[][] squares = new boolean[board.length][board.length];

      for (int i = 0; i < board.length; ++i) {
        for (int j = 0; j < board.length; ++j) {
          if (board[i][j] == '.') {
            continue;
          }
          int num = board[i][j] - '1';
          int index = getSquaresIndex(i, j);
          if (rows[i][num] || columns[j][num] || squares[index][num]) {
            return false;
          }
          rows[i][num] = true;
          columns[j][num] = true;
          squares[index][num] = true;
        }
      }

      return true;
    }

    private int getSquaresIndex(int i, int j) {
      i /= 3;
      j /= 3;

      return i * 3 + j;
    }

  }

}
